<template>
  <div>
    <h1>巡检任务管理</h1>
    <el-button @click="showCreateForm =!showCreateForm">
      {{ showCreateForm? '隐藏创建任务表单' : '创建任务' }}
    </el-button>
    <!-- 创建任务表单 -->
    <el-form v-if="showCreateForm" label-width="120px">
      <el-form-item label="设备ID">
        <el-select v-model="task.device_id" placeholder="请选择设备ID">
          <el-option v-for="deviceId in deviceIds" :key="deviceId" :label="deviceId" :value="deviceId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="巡检人员ID">
        <el-select v-model="task.inspector_id" placeholder="请选择巡检人员ID">
          <el-option v-for="inspectorId in inspectorIds" :key="inspectorId" :label="inspectorId" :value="inspectorId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划巡检时间">
        <el-date-picker
            v-model="task.scheduled_time"
            type="datetime"
            placeholder="请选择计划巡检时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="createNewTask">提交创建</el-button>
      </el-form-item>
    </el-form>
    <!-- 任务列表展示 -->
    <el-table :data="tasks" stripe>
      <el-table-column prop="id" label="任务ID"></el-table-column>
      <el-table-column prop="device_id" label="设备ID"></el-table-column>
      <el-table-column prop="inspector_id" label="巡检人员ID"></el-table-column>
      <el-table-column prop="status" label="任务状态"></el-table-column>
      <el-table-column prop="scheduled_time" label="计划巡检时间"></el-table-column>
      <el-table-column prop="created_at" label="巡检开始时间"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">修改任务信息</el-button>
          <el-button type="text" @click="deleteTask(row.id)">删除任务</el-button>
          <el-button type="text" @click="fetchTaskById(row.id)">查询任务</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 更新任务状态表单 -->
    <el-form v-if="showUpdateForm" label-width="120px">
      <el-form-item label="更新设备ID">
        <el-select v-model="task.device_id" placeholder="请选择更新后的设备ID">
          <el-option v-for="deviceId in deviceIds" :key="deviceId" :label="deviceId" :value="deviceId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更新巡检人员ID">
        <el-select v-model="task.inspector_id" placeholder="请选择更新后的巡检人员ID">
          <el-option v-for="inspectorId in inspectorIds" :key="inspectorId" :label="inspectorId" :value="inspectorId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更新计划巡检时间">
        <el-date-picker
            v-model="task.scheduled_time"
            type="datetime"
            placeholder="请选择更新后的计划巡检时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新任务状态">
        <el-select v-model="task.status" placeholder="请选择更新后的任务状态">
          <el-option value="未开始">未开始</el-option>
          <el-option value="进行中">进行中</el-option>
          <el-option value="已完成">已完成</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="updateTask">提交更新</el-button>
      </el-form-item>
    </el-form>
    <!-- 展示单个任务详情 -->
    <el-dialog v:visible.sync="showTaskDetails" title="任务详情">
      <el-form label-width="120px">
        <el-form-item label="任务ID">
          <span>{{ singleTask.id }}</span>
        </el-form-item>
        <el-form-item label="设备ID">
          <span>{{ singleTask.device_id }}</span>
        </el-form-item>
        <el-form-item label="巡检人员ID">
          <span>{{ singleTask.inspector_id }}</span>
        </el-form-item>
        <el-form-item label="任务状态">
          <span>{{ singleTask.status }}</span>
        </el-form-item>
        <el-form-item label="计划巡检时间">
          <span>{{ singleTask.scheduled_time }}</span>
        </el-form-item>
        <el-form-item label="任务创建时间">
          <span>{{ singleTask.created_at }}</span>
        </el-form-item>
        <el-form-item label="设备位置">
          <span>{{ singleDevice?.location }}</span>
        </el-form-item>
        <el-form-item label="设备描述">
          <span>{{ singleDevice?.description }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTaskDetails = false">关闭详情</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      showCreateForm: false,
      showUpdateForm: false,
      showTaskDetails: false,
      task: {
        device_id: '',
        inspector_id: '',
        status: '未开始',
        scheduled_time: '',
        created_at: ''
      },
      tasks: [],
      deviceIds: [],
      inspectorIds: [],
      selectedTaskId: '',
      singleTask: null,
      singleDevice: null
    };
  },
  async created() {
    await Promise.all([
      this.fetchTasks(),
      this.fetchDeviceIds(),
      this.fetchInspectorIds()
    ]);
  },
  methods: {
    async createNewTask() {
      try {
        this.task.created_at = new Date(this.task.scheduled_time).toISOString();
        const response = await axios.post('/api/tasks', this.task);
        if (response.status === 200) {
          await this.fetchTasks();
          this.task = {
            device_id: '',
            inspector_id: '',
            status: '未开始',
            scheduled_time: ''
          };
          this.showCreateForm = false;
        }
      } catch (error) {
        console.error('创建任务失败', error);
      }
    },
    async fetchTasks() {
      try {
        const response = await axios.get('/api/tasks');
        if (response.status === 200) {
          this.tasks = response.data;
        }
      } catch (error) {
        console.error('获取任务列表失败', error);
      }
    },
    async updateTask() {
      if (!this.selectedTaskId) {
        console.error('请选择要更新的任务');
        return;
      }
      try {
        const updatedTask = {
          device_id: this.task.device_id,
          inspector_id: this.task.inspector_id,
          status: this.task.status,
          scheduled_time: this.task.scheduled_time
        };
        const response = await axios.put(`/api/tasks/${this.selectedTaskId}`, updatedTask);
        if (response.status === 200) {
          await this.fetchTasks();
          this.showUpdateForm = false;
        }
      } catch (error) {
        console.error('更新任务信息失败', error);
      }
    },
    async fetchTaskById(id) {
      try {
        const taskResponse = await axios.get(`/api/tasks/${id}`);
        if (taskResponse.status === 200) {
          this.singleTask = taskResponse.data;
          const deviceId = this.singleTask.device_id;
          if (deviceId) {
            const deviceResponse = await axios.get(`/api/devices/${deviceId}`);
            if (deviceResponse.status === 200) {
              this.singleDevice = deviceResponse.data;
            } else {
              console.error('获取设备信息失败');
              this.singleDevice = null;
            }
          } else {
            console.error('设备ID无效');
            this.singleDevice = null;
          }
          this.showTaskDetails = true;
        }
      } catch (error) {
        console.error('查询任务失败', error);
        this.singleDevice = null;
      }
    },
    async deleteTask(id) {
      if (confirm('确定要删除该任务吗？')) {
        try {
          const response = await axios.delete(`/api/tasks/${id}`);
          if (response.status === 200) {
            await this.fetchTasks();
          }
        } catch (error) {
          console.error('删除任务失败', error);
        }
      }
    },
    async fetchDeviceIds() {
      try {
        const response = await axios.get('/api/devices');
        this.deviceIds = response.data.map(device => device.id);
      } catch (error) {
        console.error('获取设备ID列表失败:', error);
      }
    },
    async fetchInspectorIds() {
      try {
        const response = await axios.get('/api/users/getUserAll');
        this.inspectorIds = response.data
            .filter(user => user.role === '巡检员')
            .map(user => user.id);
      } catch (error) {
        console.error('获取巡检人员ID列表失败:', error);
      }
    },
    handleEdit(row) {
      this.selectedTaskId = row.id;
      this.task = { ...row };
      this.showUpdateForm = true;
    }
  }
};
</script>

<style scoped>
/* 可根据需要添加额外的自定义样式 */
</style>